const ini = require('node-ini');
ini.encoding = 'utf-8';
const http = require('http');
const path = require("path");
const fs = require('fs');
const crypUtil = require('../../../static/utils/CrypUtil');
const readIniFile = require('../readini')

const headerMap = new Map();
headerMap.set(".asf", "video/x-ms-asf");
headerMap.set(".asx", "video/x-ms-asf");
headerMap.set(".avi", "video/x-msvideo");
headerMap.set(".bin", "application/octet-stream");
headerMap.set(".cco", "application/x-cocoa");
headerMap.set(".crt", "application/x-x509-ca-cert");
headerMap.set(".css", "text/css");
headerMap.set(".deb", "application/octet-stream");
headerMap.set(".der", "application/x-x509-ca-cert");
headerMap.set(".dll", "application/octet-stream");
headerMap.set(".dmg", "application/octet-stream");
headerMap.set(".ear", "application/java-archive");
headerMap.set(".eot", "application/octet-stream");
headerMap.set(".exe", "application/octet-stream");
headerMap.set(".flv", "video/x-flv");
headerMap.set(".gif", "image/gif");
headerMap.set(".hqx", "application/mac-binhex40");
headerMap.set(".htc", "text/x-component");
headerMap.set(".htm", "text/html");
headerMap.set(".html", "text/html");
headerMap.set(".ico", "image/x-icon");
headerMap.set(".img", "application/octet-stream");
headerMap.set(".iso", "application/octet-stream");
headerMap.set(".jar", "application/java-archive");
headerMap.set(".jardiff", "application/x-java-archive-diff");
headerMap.set(".jng", "image/x-jng");
headerMap.set(".jnlp", "application/x-java-jnlp-file");
headerMap.set(".jpeg", "image/jpeg");
headerMap.set(".jpg", "image/jpeg");
headerMap.set(".js", "application/x-javascript");
headerMap.set(".mml", "text/mathml");
headerMap.set(".mng", "video/x-mng");
headerMap.set(".mov", "video/quicktime");
headerMap.set(".mp3", "audio/mpeg");
headerMap.set(".mpeg", "video/mpeg");
headerMap.set(".mpg", "video/mpeg");
headerMap.set(".msi", "application/octet-stream");
headerMap.set(".msm", "application/octet-stream");
headerMap.set(".msp", "application/octet-stream");
headerMap.set(".pdb", "application/x-pilot");
headerMap.set(".pdf", "application/pdf");
headerMap.set(".pem", "application/x-x509-ca-cert");
headerMap.set(".pl", "application/x-perl");
headerMap.set(".pm", "application/x-perl");
headerMap.set(".png", "image/png");
headerMap.set(".prc", "application/x-pilot");
headerMap.set(".ra", "audio/x-realaudio");
headerMap.set(".rar", "application/x-rar-compressed");
headerMap.set(".rpm", "application/x-redhat-package-manager");
headerMap.set(".rss", "text/xml");
headerMap.set(".run", "application/x-makeself");
headerMap.set(".sea", "application/x-sea");
headerMap.set(".shtml", "text/html");
headerMap.set(".sit", "application/x-stuffit");
headerMap.set(".swf", "application/x-shockwave-flash");
headerMap.set(".tcl", "application/x-tcl");
headerMap.set(".tk", "application/x-tcl");
headerMap.set(".txt", "text/plain");
headerMap.set(".war", "application/java-archive");
headerMap.set(".wbmp", "image/vnd.wap.wbmp");
headerMap.set(".wmv", "video/x-ms-wmv");
headerMap.set(".xml", "text/xml");
headerMap.set(".xpi", "application/x-xpinstall");
headerMap.set(".zip", "application/zip");


//全局存储数据目录
let dataDir = readDataDir();

let currentServer = null;
createServer();

// 存储已解密的key文件内容，避免频繁解密
let videoKeys = new Map();

function createServer () {
    let eduLevel = readIniFile('data', 'eduLevel');
    let port = (eduLevel === "primary" ? "38001" : "38002");
    currentServer = http.createServer(function (request, response) {
        let reqUrl = request.url;
        if (reqUrl === "/favicon.ico") {
            return;
        }

        let filePath = path.join(dataDir, "resc", reqUrl);
        let fileName = path.win32.basename(filePath);
        let fileNameExtention = fileName.substring(fileName.lastIndexOf('.'), fileName.length);
        console.log("dataDir ==> " + dataDir + " reqUrl ==> " + reqUrl + " filePath ==> " + filePath + " fileName ==> " + fileName + " fileNameExtention ==> " + fileNameExtention);

        if (headerMap.has(fileNameExtention)) {
            response.setHeader("Content-Type", headerMap.get(fileNameExtention));
        } else {
            response.setHeader("Content-Type", "application/octet-stream");
        }

        if (fileNameExtention === ".key") { // 如果请求key文件，优先从之前的缓存中读取
            if (videoKeys.has(fileName)) {
                let keyVaule = videoKeys.get(fileName);
                response.setHeader("Content-Length", keyVaule.length);
                response.write(keyVaule);
                response.end();
                return;
            }
        }

        //打开文件读取
        fs.open(filePath, 'r', function (err, fd) {
            if (err) return;
            // 读取文件
            //首先创建buffer，文件读取到buffer中
            let size = fs.statSync(filePath).size;//计算文件长度
            let buf = Buffer.alloc(size);
            fs.read(fd, buf, 0, size, 0, function (err, bytesRead, buffer) {
                if (err) {
                    response.write('404');
                } else {
                    if (fileNameExtention === ".key") {//如果是.key文件的话，就需要解密再返回
                        let key = "12345678" + "kdjerewd" + "093-1=32" + "abCsd.ed";
                        let descrypt = crypUtil.aesDecrypt(buffer.toString(), key);
                        console.log('解密后的keyValue--------->' + descrypt);
                        descrypt = new Buffer(descrypt, 'base64');
                        response.setHeader("Content-Length", descrypt.length);
                        response.write(descrypt);

                        videoKeys.set(fileName, descrypt);
                    } else {
                        response.setHeader("Content-Length", bytesRead);
                        response.write(buffer);
                    }
                }
                response.end();
                // 手动关闭下已打开的文件handle
                fs.closeSync(fd);
            })
        });
    }).listen(port, function (err) {
        if (err) {
            console.log(err)
            console.log("监听38001端口失败！")
        }
    })
}

function readDataDir () {
    //全局存储数据目录
    let dataDir = readIniFile('data', 'dataDir');
    if (dataDir === "self") {//代表是当前目录
        if (process.env.NODE_ENV === 'production') {
            dataDir = path.dirname(process.execPath) + '/resources/data/';
        } else {
            dataDir = './data/';
        }
    } else if (dataDir === "low-update") {
        dataDir = path.dirname(process.execPath) + '/html/';
    }
    let resc = path.join(dataDir, "resc");
    if (!fs.existsSync(resc)) {
        fs.mkdirSync(resc);
    }
    if (!fs.existsSync(path.join(resc, "Collection"))) {
        fs.mkdirSync(path.join(resc, "Collection"));
    }
    if (!fs.existsSync(path.join(resc, "courseware"))) {
        fs.mkdirSync(path.join(resc, "courseware"));
    }
    if (!fs.existsSync(path.join(resc, "HeatMap"))) {
        fs.mkdirSync(path.join(resc, "HeatMap"));
    }
    if (!fs.existsSync(path.join(resc, "InnerStruct"))) {
        fs.mkdirSync(path.join(resc, "InnerStruct"));
    }
    if (!fs.existsSync(path.join(resc, "MultiAngle"))) {
        fs.mkdirSync(path.join(resc, "MultiAngle"));
    }
    if (!fs.existsSync(path.join(resc, "Partial"))) {
        fs.mkdirSync(path.join(resc, "Partial"));
    }
    if (!fs.existsSync(path.join(resc, "PolyvVideo"))) {
        fs.mkdirSync(path.join(resc, "PolyvVideo"));
    }
    if (!fs.existsSync(path.join(resc, "BosVideo"))) {
        fs.mkdirSync(path.join(resc, "BosVideo"));
    }
    // if (!fs.existsSync(path.join(resc, "ppt"))) {
    //     fs.mkdirSync(path.join(resc, "ppt"));
    // }
    if (!fs.existsSync(path.join(resc, "Quiz"))) {
        fs.mkdirSync(path.join(resc, "Quiz"));
    }
    if (!fs.existsSync(path.join(resc, "Rotation360"))) {
        fs.mkdirSync(path.join(resc, "Rotation360"));
    }
    if (!fs.existsSync(path.join(resc, "TimeLapse"))) {
        fs.mkdirSync(path.join(resc, "TimeLapse"));
    }
    if (!fs.existsSync(path.join(resc, "VirtualReality"))) {
        fs.mkdirSync(path.join(resc, "VirtualReality"));
    }
    if (!fs.existsSync(path.join(resc, "ZoomIn"))) {
        fs.mkdirSync(path.join(resc, "ZoomIn"));
    }
    if (!fs.existsSync(path.join(resc, "VirtualLab"))) {
        fs.mkdirSync(path.join(resc, "VirtualLab"));
    }
    if (!fs.existsSync(path.join(resc, "VrHotspot"))) {
        fs.mkdirSync(path.join(resc, "VrHotspot"));
    }
    if (!fs.existsSync(path.join(resc, "StepExplore"))) {
        fs.mkdirSync(path.join(resc, "StepExplore"));
    }
    if (!fs.existsSync(path.join(resc, "MindMap"))) {
        fs.mkdirSync(path.join(resc, "MindMap"));
    }
    if (!fs.existsSync(path.join(resc, "PaperFile"))) {
        fs.mkdirSync(path.join(resc, "PaperFile"));
    }
    if (!fs.existsSync(path.join(resc, "user"))) {
        fs.mkdirSync(path.join(resc, "user"))
    }
    if (!fs.existsSync(path.join(resc, "user", "mindMap"))) {
        fs.mkdirSync(path.join(resc, "user", "mindMap"))
    }
    if (!fs.existsSync(path.join(resc, "user", "charts"))) {
        fs.mkdirSync(path.join(resc, "user", "charts"))
    }
    if (!fs.existsSync(path.join(resc, "user", "ppt"))) {
        fs.mkdirSync(path.join(resc, "user", "ppt"))
    }
    if (!fs.existsSync(path.join(resc, "user",'pdf'))) {
        fs.mkdirSync(path.join(resc, "user",'pdf'))
    }
    if (!fs.existsSync(path.join(resc, "user",'word'))) {
        fs.mkdirSync(path.join(resc, "user",'word'))
    }
    if (!fs.existsSync(path.join(resc, "user",'img'))) {
        fs.mkdirSync(path.join(resc, "user",'img'))
    }
    if (!fs.existsSync(path.join(resc, "user",'video'))) {
        fs.mkdirSync(path.join(resc, "user",'video'))
    }
    if (!fs.existsSync(path.join(resc, "user",'audio'))) {
        fs.mkdirSync(path.join(resc, "user",'audio'))
    }
    return path.resolve(dataDir);
}
module.exports = currentServer;
